#include "GLRect.h"
#include "RenderController.h"
#include "common.h"
void GLRect::initData()
{
	if (mInited)
	{
		return;
	}
	mInited = true;
	glGenBuffers(1, &mVBO);
	// 生成VAO
	glGenVertexArrays(1, &mVAO);

	glBindVertexArray(mVAO);
	{
		const uint32_t cVertexLocation = 0;
		glBindBuffer(GL_ARRAY_BUFFER, mVBO);
		glEnableVertexAttribArray(cVertexLocation);
		glVertexAttribPointer(cVertexLocation, 3, GL_FLOAT, GL_FALSE, sizeof(QVector3D), nullptr);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
	}
	glBindVertexArray(0);

	updateData();
}
void GLRect::updateData()
{
	auto windowSize = gController->viewSize() * qApp->devicePixelRatio();

	auto verPosStart = posNormal(mStart, windowSize);

	auto verPosStop = posNormal(mStop, windowSize);

	mVertices.clear();
	mVertices << QVector3D(verPosStart.x(), verPosStart.y(), 0.0);
	mVertices << QVector3D(verPosStop.x(), verPosStart.y(), 0.0);

	mVertices << QVector3D(verPosStop.x(), verPosStart.y(), 0.0);
	mVertices << QVector3D(verPosStop.x(), verPosStop.y(), 0.0);

	mVertices << QVector3D(verPosStop.x(), verPosStop.y(), 0.0);
	mVertices << QVector3D(verPosStart.x(), verPosStop.y(), 0.0);

	mVertices << QVector3D(verPosStart.x(), verPosStop.y(), 0.0);
	mVertices << QVector3D(verPosStart.x(), verPosStart.y(), 0.0);
	glBindBuffer(GL_ARRAY_BUFFER, mVBO);
	{
		glBufferData(GL_ARRAY_BUFFER, sizeof(QVector3D) * mVertices.size(), mVertices.constData(), GL_STATIC_DRAW);
	}
	glBindBuffer(GL_ARRAY_BUFFER, 0);
}

void GLRect::paint(QOpenGLShaderProgram* program, const QMatrix4x4& mvpMat)
{
	if (!mVisible)
	{
		return;
	}
	if (!program->bind())
	{
		return;
	}
	glBindVertexArray(mVAO);
	{
		glLineWidth(mLineWidth);
		program->setUniformValue("qt_ModelViewProjectionMatrix", mvpMat);
		program->setUniformValue("outColor0", mColor);
		glDrawArrays(GL_LINES, 0, mVertices.size());
	}
	glBindVertexArray(0);
}
